const assert = require('http-assert')
const multer = require("multer")
const {uploadPath, uploadURL, maxFileSize} = require('../config')
const path = require('path')
const fs = require('fs')

const allUploadType = ["banner", "news", "other"]
const tips = {
  "banner": '添加轮播图成功',
  "news": '添加新闻图片成功',
  "other": '上传成功'
}
const storage = multer.diskStorage({
  //存储位置
  destination(req, res, cb) {
    const uploadType = req.params.type || req.body.type || 'other'
    const filePath = path.join(uploadPath, uploadType)
    fs.existsSync(filePath) || fs.mkdirSync(filePath);
    cb(null, filePath);
  },
  filename(req, file, cb) {
    const {ext, name} = path.parse(file.originalname)
    cb(null, decodeURI(name + '_' + Date.now() + ext));
  }
})
const upload = multer({
  fileFilter(req, file, callback) {
    // 解决中文名乱码的问题 latin1 是一种编码格式
    file.originalname = Buffer.from(file.originalname, "latin1").toString(
      "utf8"
    );
    callback(null, true);
  },
  storage,
  limits: {
    fileSize: maxFileSize
  }
})


exports.upload = upload.any()

exports.uploadType = function (isNext) {
  return async (req, res, next) => {
    try {
      let tip = null
      const uploadType = req.params.type || req.body.type || 'other'
      if (allUploadType.includes(uploadType)) {
        tip = tips[uploadType]
      } else {
        return res.send({
          code: 422,
          message: '传参错误'
        })
      }
      let fileURLS = req.files.map(item => {
        let {destination, filename} = item
        return path.join(path.parse(destination).name, filename).replace(/\\/g, '/').replace('http:/', 'http://')
      })
      if (isNext) {
        req.imgUrl = fileURLS[0]
        next()
      } else {
        res.send({
          code: 20000,
          data: {
            message: tip,
            imgUrl: uploadURL + fileURLS[0]
          }
        })
      }


    } catch (err) {
      console.log(err)
      next(err)
    }

  }

}


